﻿using CKS2320.Common;
using CKS2320.Common.Model;
using CKS2320.Common.Transfer;
using CKS2320.Common.Utils;
using CKS2320.Domain.DBEntity;
using CKS2320.Repository;
using CKS2320.Repository.Interface;
using CKS2320.Service.Interface;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Org.BouncyCastle.Ocsp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using static NPOI.HSSF.Util.HSSFColor;

namespace CKS2320.Service
{
    public class CksLargeTotalService : ICksLargeTotalService
    {
        private ICksLargeTotalRepository _cksLargeTotalRepository;
        public CksLargeTotalService(ICksLargeTotalRepository cksLargeTotalRepository)
        {
            _cksLargeTotalRepository = cksLargeTotalRepository;
        }
        public ResultReturn GetTotalData(TotalReq totalReq)
        {
            Hashtable hashtable = new Hashtable();
            List<AllproduceDto> List1 = new List<AllproduceDto>();
            List<AllproduceDto> List2 = new List<AllproduceDto>();
            DateTime dateTime = DateTime.Now;
            string? PuStartTime = null;
            string? PuEndTime = null;
            #region 判断时间格式是否正确
            try
            {
                if (!string.IsNullOrEmpty(totalReq.StartTime) && !string.IsNullOrEmpty(totalReq.EndTime))
                {
                    DateTime st = DateTime.Parse(totalReq.StartTime);
                    DateTime et = DateTime.Parse(totalReq.EndTime);
                    PuStartTime = st.ToString("yyyy-MM-dd") + " 00:00:00 ";
                    PuEndTime = et.ToString("yyyy-MM-dd") + " 23:59:59 ";
                }
                else
                {
                    PuStartTime = dateTime.ToString("yyyy-MM-dd") + " 00:00:00 ";
                    PuEndTime = dateTime.ToString("yyyy-MM-dd") + " 23:59:59";
                }
            }
            catch (Exception ex)
            {
                if (totalReq.Language.ToUpper() == "EN")
                {
                    return MessageInfoUtils.Fail("Invalid time format！");
                }
                if (totalReq.Language.ToUpper() == "ES")
                {
                    return MessageInfoUtils.Fail("Formato de tiempo no válido！");
                }
                return MessageInfoUtils.Fail("无效的时间格式！");
            }
            #endregion
            try
            {
                #region 生产数量近5日
                for (int i = 1; i <= 5; i++)
                {
                    AllproduceDto allproduce = new AllproduceDto();
                    string time = dateTime.AddDays(-i).ToString("yyyy-MM-dd");
                    string dd = dateTime.AddDays(-i).ToString("dd");
                    string Starttime = time + " 00:00:00";
                    string Endtime = time + " 23:59:59";

                    allproduce.DateDD = int.Parse(dd).ToString() + LanguageConversion(totalReq.Language);
                    int count = _cksLargeTotalRepository.GetAllCount(Starttime, Endtime, true);
                    allproduce.Count = count;
                    List1.Add(allproduce);
                }
                hashtable.Add("shengchan", List1);
                #endregion
                #region 成品数量近5日
                for (int i = 1; i <= 5; i++)
                {
                    AllproduceDto allproduce = new AllproduceDto();
                    string time = dateTime.AddDays(-i).ToString("yyyy-MM-dd");
                    string dd = dateTime.AddDays(-i).ToString("dd");
                    string Starttime = time + " 00:00:00";
                    string Endtime = time + " 23:59:59";
                    allproduce.DateDD = int.Parse(dd).ToString() + LanguageConversion(totalReq.Language);
                    int count = _cksLargeTotalRepository.GetAllCount(Starttime, Endtime, false);
                    allproduce.Count = count;
                    List2.Add(allproduce);
                }
                hashtable.Add("chengpin", List2);
                #endregion
                #region 不良品数量当日
                string DefectiveStarttime = "";
                string DefectivesEndtime = "";
                //没有传时间就取当天的

                List<DefectiveDto> List3 = new List<DefectiveDto>();
                List<DefectiveDto> defectiveDtos1 = _cksLargeTotalRepository.GetdefectiveList(PuStartTime, PuEndTime);
                List<IGrouping<string, DefectiveDto>> lgy = defectiveDtos1.GroupBy(p => p.PartCode).ToList();
                //同一产品号相加
                foreach (var item in lgy)
                {
                    DefectiveDto dto = new DefectiveDto();
                    int? num = 0;
                    dto.PartCode = item.Key;
                    foreach (var dt in item)
                    {
                        num += dt.Num;
                    }
                    dto.Num = num;
                    List3.Add(dto);
                }
                hashtable.Add("buliang", List3.OrderByDescending(p => p.Num).Take(5).ToList());
                #endregion
                #region 总和成品数量近5日
                List<TotalproduceDto> totalList = new List<TotalproduceDto>();
                string timeNew = dateTime.ToString("yyyy-MM-dd");
                //近五日的结束时间  包含今天
                string EndtimeNew = timeNew + " 23:59:59";
                //近五日的开始时间
                string StarttimeNew = dateTime.AddDays(-5).ToString("yyyy-MM-dd") + " 00:00:00 ";
                //一共三个检测台
                for (int t = 1; t <= 3; t++)
                {
                    List<AllStationCodeDto> AllStationCodeDtoLsit = _cksLargeTotalRepository.GetTotalCount1(StarttimeNew, EndtimeNew, t);
                    TotalproduceDto totaldto = new TotalproduceDto();
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    dic.Add(LanguageToCn(totalReq.Language, "检测台"), "OP" + t + "0");
                    dic.Add(LanguageToCn(totalReq.Language, "总和"), AllStationCodeDtoLsit.Count.ToString());
                    for (int i = 0; i <= 5; i++)
                    {
                        string timenew = null;
                        string time = dateTime.AddDays(-i).ToString("yyyy-MM-dd");
                        string dd = dateTime.AddDays(-i).ToString("dd");
                        string Starttime = time + " 00:00:00";
                        string Endtime = time + " 23:59:59";
                        if (i == 0)
                        {
                            timenew = LanguageToCn(totalReq.Language, "当日");
                        }
                        else
                        {
                            timenew = int.Parse(dd).ToString() + LanguageConversion(totalReq.Language);
                        }
                        //从当前的工位分组下AllDaysList中找对应每天的数量
                        int count = AllStationCodeDtoLsit.Where(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime)).ToList().Count;
                        dic.Add(timenew, count.ToString());
                    }
                    totaldto.dicy = dic;
                    totalList.Add(totaldto);
                }
                hashtable.Add("op", totalList);
                #endregion
                List<string> str = new List<string>();
                str.Add(LanguageToCn(totalReq.Language, "检测台"));
                str.Add(LanguageToCn(totalReq.Language, "总和"));
                for (int i = 0; i <= 5; i++)
                {
                    string timenew = null;
                    string time = dateTime.AddDays(-i).ToString("yyyy-MM-dd");
                    string dd = dateTime.AddDays(-i).ToString("dd");
                    string Starttime = time + " 00:00:00";
                    string Endtime = time + " 23:59:59";
                    if (i == 0)
                    {
                        timenew = LanguageToCn(totalReq.Language, "当日");
                    }
                    else
                    {
                        timenew = int.Parse(dd).ToString() + LanguageConversion(totalReq.Language);
                    }
                    str.Add(timenew);
                }
                hashtable.Add("tiemtype", str);
            }
            catch (Exception ex)
            {
                return MessageInfoUtils.Fail(ex.ToString());
            }
            return MessageInfoUtils.Success(hashtable);
        }
        public string LanguageConversion(string language)
        {
            if (language.ToUpper() == "CN")
            {
                return "日";
            }
            else if (language.ToUpper() == "EN")
            {
                return "th";
            }
            else if (language.ToUpper() == "ES")
            {
                return "día";
            }
            else
            {
                return "日";
            }

        }
        public string LanguageToCn(string language, string str)
        {
            if (language.ToUpper() == "CN")
            {
                if (str == "当日")
                {
                    return "当日";
                }
                else if (str == "检测台")
                {
                    return "检测台";
                }
                else if (str == "总和")
                {
                    return "总和";
                }
                else
                {
                    return null;
                }
            }
            else if (language.ToUpper() == "EN")
            {
                if (str == "当日")
                {
                    return "today";
                }
                else if (str == "检测台")
                {
                    return "Detection station";
                }
                else if (str == "总和")
                {
                    return "sum";
                }
                else
                {
                    return null;
                }
            }
            else if (language.ToUpper() == "ES")
            {
                if (str == "当日")
                {
                    return "Hoy.";
                }
                else if (str == "检测台")
                {
                    return "Mesa de pruebas";
                }
                else if (str == "总和")
                {
                    return "Suma";
                }
                else
                {
                    return null;
                }
            }
            else
            {
                if (str == "当日")
                {
                    return "当日";
                }
                else if (str == "检测台")
                {
                    return "检测台";
                }
                else if (str == "总和")
                {
                    return "总和";
                }
                else
                {
                    return null;
                }
            }

        }
        /// <summary>
        /// 检测记录导出
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public ResultReturn ExportQueryList(TotalReq req)
        {
            var query = _cksLargeTotalRepository.ExportQueryList(PLCRunTypeEnum.A).OrderByDescending(p => p.CreatedTime).ToList();
            query.AddRange(_cksLargeTotalRepository.ExportQueryList(PLCRunTypeEnum.B).OrderByDescending(p => p.CreatedTime).ToList());
            if (query != null && query.Any())
            {
                foreach (var item in query)
                {
                    item.DetectedType = TransferDic.GetMessage(item.DetectedType, req.Language ?? "zh");
                }
            }
            List<ReturnKeyValueList> returnKeyValueLists = ModelUtils.ReturnTransfor(query);
            FileOperation fileOperation = new();
            return fileOperation.FileExport(returnKeyValueLists, "检测记录", "Export_" + DateTime.Now.ToString("yyyyMMddHHmms"));
        }
        public ResultReturn ExportQueryListNew(TotalReq totalReq)
        {
            List<PerformanceRecord> ExportRecordList = _cksLargeTotalRepository.ExportRecord(totalReq).Result;
            List<ExportQueryCount> listCount = _cksLargeTotalRepository.ExportQueryListCount(totalReq).Result;
            List<ExportQueryModel> result = _cksLargeTotalRepository.ExportQueryListNew(totalReq).Result;
            List<Equipmentfailurehistory> Alarm = _cksLargeTotalRepository.ExportAlarm(totalReq).Result;

            FileOperation fileOperation = new();
            return fileOperation.FileExportresuft(result, listCount, ExportRecordList, Alarm, "检测记录", "Export_" + DateTime.Now.ToString("yyyyMMddHHmms"));
        }


        public ResultReturn ExportQuerydetails(TotalReq req)
        {
            Hashtable result = new Hashtable();
            result = _cksLargeTotalRepository.ExportQuerydetails(req);
            FileOperation fileOperation = new();
            return fileOperation.FileExportForHashtable(result, "检测详细记录", "Export_" + DateTime.Now.ToString("yyyyMMddHHmms"));
        }


        public ResultReturn GetThicknessList(TotalReq totalReq)
        {
            List<Detectiondetail> list = _cksLargeTotalRepository.GetThicknessList(totalReq);
            if (list != null && list.Any())
            {
                foreach (var item in list)
                {
                    item.DetectedType = TransferDic.GetMessage(item.DetectedTypeDisplay, totalReq.Language ?? "zh");
                }
            }
            List<Detectiondetail> list1 = list.Where(p => p.DetectedTypeDisplay == "FCT").ToList();
            List<Detectiondetail> list2 = list.Where(p => p.DetectedTypeDisplay == "BCT").ToList();
            List<ThicknessResponse> htlist = new List<ThicknessResponse>();
            if (list1.Count > 0 && list2.Count > 0)
            {
                for (global::System.Int32 i = 0; i < list1.Count; i++)
                {
                    Detectiondetail model = list1[i];
                    Detectiondetail mode2 = list2[i];
                    ThicknessResponse ht = new ThicknessResponse();
                    ht.DetectedTypeFront = model?.DetectedType + (i + 1);
                    ht.FrontData = model?.DetectedData.ToString();
                    ht.DetectedTypeBack = mode2?.DetectedType + (i + 1);
                    ht.BackData = mode2?.DetectedData.ToString();
                    htlist.Add(ht);
                }
            }
            return MessageInfoUtils.Success(htlist);
        }
        /// <summary>
        /// 获取检测记录
        /// </summary>
        public ResultReturn DetectionHistoryNew(TotalReq totalReq)
        {
            DataQueryResponseNew result = _cksLargeTotalRepository.QueryListCountNew(totalReq).Result;
            return MessageInfoUtils.Success(result);
        }
        public ResultReturn DetectionHistory(TotalReq totalReq)
        {
            DataQueryResponse result = _cksLargeTotalRepository.QueryListCount();
            var indicatorToleranceZones = _cksLargeTotalRepository.GetIndicatorToleranceZones();

            var queryA = _cksLargeTotalRepository.QueryList(totalReq, PLCRunTypeEnum.A);
            result.list.AddRange(_cksLargeTotalRepository.QueryListDetail(queryA, indicatorToleranceZones, PLCRunTypeEnum.A));

            var queryB = _cksLargeTotalRepository.QueryList(totalReq, PLCRunTypeEnum.B);
            result.list.AddRange(_cksLargeTotalRepository.QueryListDetail(queryB, indicatorToleranceZones, PLCRunTypeEnum.B));

            if (result.list != null && result.list.Any())
            {
                foreach (var item in result.list)
                {
                    item.DetectedType = TransferDic.GetMessage(item.DetectedType, totalReq.Language ?? "zh");
                }
            }
            return MessageInfoUtils.Success(result);
        }
        /// <summary>
        /// 历史数据趋势
        /// </summary>
        /// <param name="req"></param>
        public ResultReturn HistoryDataTrends(TrendsReq req)
        {
            if (string.IsNullOrEmpty(req.Date))
                req.Date = DateTime.Now.ToString("yyyy-MM-dd");
            else
                req.Date = Convert.ToDateTime(req.Date).ToString("yyyy-MM-dd");

            HistoryDataTrendsPackResponse result = new();
            var indicatorToleranceZones = _cksLargeTotalRepository.GetIndicatorToleranceZones();
            if (req.BOW == true)
            {
                var detailList = _cksLargeTotalRepository.HistoryDataTrends(req.Date, 1);
                if (detailList != null)
                {
                    for (int i = 0; i < 24; i++)
                    {
                        HistoryDataTrendsPack pack = new()
                        {
                            hour = i.ToString(),
                            indicator = indicatorToleranceZones.FirstOrDefault(p => p.Content == "水平拱曲度").Indicator.Value.ToString(),
                            data = detailList.Where(p => p.CreatedTime.Value.Hour == i).Select(p => p.DetectedData).ToList()
                        };
                        result.bow.Add(pack);
                    }
                }
            }
            if (req.Camble == true)
            {
                var detailList = _cksLargeTotalRepository.HistoryDataTrends(req.Date, 2);
                if (detailList != null)
                {
                    for (int i = 0; i < 24; i++)
                    {
                        HistoryDataTrendsPack pack = new()
                        {
                            hour = i.ToString(),
                            indicator = indicatorToleranceZones.FirstOrDefault(p => p.Content == "水平扭曲度").Indicator.Value.ToString(),
                            data = detailList.Where(p => p.CreatedTime.Value.Hour == i).Select(p => p.DetectedData).ToList()
                        };
                        result.camble.Add(pack);
                    }
                }
            }
            if (req.EntireLength == true)
            {
                var detailList = _cksLargeTotalRepository.HistoryDataTrends(req.Date, 10);
                if (detailList != null)
                {
                    for (int i = 0; i < 24; i++)
                    {
                        HistoryDataTrendsPack pack = new()
                        {
                            hour = i.ToString(),
                            indicator = indicatorToleranceZones.FirstOrDefault(p => p.Content == "总长").Indicator.Value.ToString(),
                            data = detailList.Where(p => p.CreatedTime.Value.Hour == i).Select(p => p.DetectedData).ToList()
                        };
                        result.entireLength.Add(pack);
                    }
                }
            }

            return MessageInfoUtils.Success(result);
        }


        /// <summary>
        /// 指标 公差带
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Indicatortolerancezone> GetIndicatorToleranceZones()
        {
            return _cksLargeTotalRepository.GetIndicatorToleranceZones();
        }
        public ResultReturn GetToDoMesData()
        {
            Hashtable model = new Hashtable();
            model = _cksLargeTotalRepository.GetToDoMesData();
            return MessageInfoUtils.Success(model);
        }
    }
}
